<template>
  <div class="channels">
    <!-- 我的频道 -->
    <div class="panle">
      <div class="title">
        <span>我的频道</span>
        <van-button
          plain
          type="warning"
          size="mini"
          @click="delShow = !delShow"
          >{{ delShow ? "取消" : "编辑" }}</van-button
        >
      </div>
      <van-grid>
        <van-grid-item
          v-for="(item, index) in ownChannels"
          :key="item.id"
          :class="{ active: index == value }"
          @click="changeActive(index)"
        >
          {{ item.name }}
          <van-icon
            class="my-icon"
            name="cross"
            v-show="delShow && index != 0"
            @click="doDel(index)"
          />
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 可选频道 -->
    <div class="panle">
      <div class="title">
        <span>可选频道</span>
      </div>
      <van-grid>
        <van-grid-item
          v-for="item in optList"
          :key="item.id"
          @click="addChannels(item)"
        >
          {{ item.name }}
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { setChannelsAPI } from "@/api";
import { saveChannels } from "@/utils/storage";
export default {
  data() {
    return {
      delShow: false,
    };
  },
  props: {
    ownChannels: {
      type: Array,
      requried: true,
    },
    allChannels: {
      type: Array,
      requried: true,
    },
    value: {
      type: Number,
      requried: true,
    },
  },
  methods: {
    async addChannels(item) {
      this.ownChannels.push(item);
      if (this.$store.state.tokenObj.token) {
        let channels = this.ownChannels.map((item, index) => {
          return { id: item.id, seq: index + 1 };
        });
        await setChannelsAPI({
          channels,
        });
      } else {
        saveChannels(this.ownChannels);
      }
    },
    changeActive(index) {
      this.$emit("input", index);
      this.$emit("close");
    },
    async doDel(index) {
      this.ownChannels.splice(index, 1);
      if (this.$store.state.tokenObj.token) {
        let channels = this.ownChannels.map((item, index) => {
          return { id: item.id, seq: index + 1 };
        });
        await setChannelsAPI({
          channels,
        });
      } else {
        saveChannels(this.ownChannels);
      }
    },
  },
  computed: {
    optList() {
      // 从所有频道里排除掉我的频道，剩余的就是可选频道
      // 换句话说，就过滤出来所有不在我的频道里的数据
      return this.allChannels.filter(
        (v) =>
          // 判断这个元素不在我的频道里，就过滤出来，否则不过滤出来
          this.ownChannels.findIndex((val) => val.id == v.id) == -1
      );
    },
  },
};
</script>

<style lang="less" scoped>
.channels {
  padding: 0px 20px;

  .title {
    margin: 10px 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .active {
    color: #f00;
  }
  .my-icon {
    position: absolute;
    top: 5px;
    right: 5px;
  }
}
</style>
